<template>
  <template v-if="modelValue.renderType">
    <div class="flex gap-2 flex-wrap" v-if="Array.isArray(JSON.parse(fieldValue))">
      <el-tag type="primary" v-if="modelValue.renderType === 'tag'" v-for="item in JSON.parse(fieldValue)">
        {{ renderValue(item) }}
      </el-tag>
      <el-text v-else v-for="item in JSON.parse(fieldValue)">
        {{ renderValue(item) }}
      </el-text>
    </div>
    <template v-else>
      <el-tag v-if="modelValue.renderType === 'tag'" :type="renderTagType">
        {{ renderValue(fieldValue) }}
      </el-tag>
      <div v-else :style="renderColor">
        {{ renderValue(fieldValue) }}
      </div>
    </template>
  </template>
  <template v-else>
    {{ renderValue(fieldValue) }}
  </template>
</template>

<script setup lang="ts">
import { FormField } from '@/components/DesignForm';
import { DesignListTableConfig } from '@/components/DesignList';

const modelValue = defineModel<DesignListTableConfig>();
const fieldValue = defineModel<any>("fieldValue");
const formItemList = defineModel<FormField[]>("formItemList");

const renderValue = (value: string) => {
  const field = formItemList.value.find(x => x.field === modelValue.value.fieldName);
  if (field && field.options) {
    const option = field.options.find(x => x.value === value);
    return option ? option.label : "";
  }
  return fieldValue.value;
}

const renderTagType = computed(() => {
  const option = getOption();
  return option ? option.type : "primary";
})

const renderColor = computed(() => {
  const option = getOption();
  return option ? `color:${option.color}` : "";
})

const getOption = () => {
  if (modelValue.value.options) {
    const option = modelValue.value.options.find(x => x.value == fieldValue.value);
    return option;
  }
  return null;
}

</script>

<style lang="scss" scoped></style>
